package devicelogic

import (
	"context"

	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpDeviceLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpDeviceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpDeviceLogic {
	return &UpDeviceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpDeviceLogic) UpDevice(in *iotpb.UpDeviceReq) (*iotpb.UpDeviceResp, error) {
	device := in.GetParams()
	if device == nil || device.GetDeptId() == 0 || device.GetProductId() == 0 ||
		device.GetName() == "" || device.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新设备失败：参数缺失"),
			tool.GetErrMsgFormat("update device"), "params is not existed", in)
	}

	// 获取数据
	one, err := l.svcCtx.IotDeviceModel.FindOne(l.ctx, device.GetId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update device"), err, in)
	}
	one.DeptId = device.GetDeptId()
	one.ProductId = device.GetProductId()
	one.Name = device.GetName()
	one.Describe = device.GetDescribe()
	one.UpdateUser = device.GetUpdateUser()

	// 更新
	err = l.svcCtx.IotDeviceModel.UpdateEx(l.ctx, nil, one)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update device"), err, in)
	}

	return &iotpb.UpDeviceResp{}, nil
}
